//
// Created by Administrator on 2023/6/26.
//
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
#include "securec.h"

int countNum = 1;
void CreatBinaryTree( char pString[][10], struct TreeNode node[100], int size, int count) {
    int start = 0;
    int curCount = 0;
    struct TreeNode curNode[100] = {0};
    while (countNum < count) {
        for (int i = 0; i < size; i++) {  // 构建一层树
            if (countNum < count) {
                node[i].left = malloc(sizeof (struct TreeNode));
                node[i].left->left = NULL;
                node[i].left->right = NULL;
                node[i].val = atoi(pString[countNum++]);
                if (node->val != -1) {
                    curNode[curCount++] =  *node[i].left;
                }
            }

            if (countNum  < count) {
                node[i].right = malloc(sizeof (struct TreeNode));
                node[i].right->left = NULL;
                node[i].right->right = NULL;
                node[i].val = atoi(pString[countNum++]);
                if (node->val != -1) {
                    curNode[curCount++] =  *node[i].right;
                }
            }
        }
        size = curCount;
        curCount = 0;
        memcpy_s(node, sizeof(node), curNode, sizeof (curNode));
        memset_s(curNode, sizeof(curNode), 0, sizeof(curNode));
    }
}

void getNum(char str[], char retStrArr[100][10], int *count) {    //1.使用strtok()实现分割
    char test[100] = {0};
    strncpy_s(test, sizeof(test) - 1, (str + 1), strlen(str) - 2);
    char *tmp = strtok(test, " ,");
    if (!tmp) {
        *count = 0;
        return;
    } else {
        strcpy_s(retStrArr[(*count)++], sizeof(retStrArr[*count]), tmp);
    }

    while (tmp != NULL) {
        tmp = strtok(NULL, " ,");
        if (NULL == tmp) {
            break;
        }
        if (strcmp(tmp, "null") == 0) {
            strcpy_s(retStrArr[(*count)++], sizeof(retStrArr[*count]), "-1");

        } else {
            strcpy_s(retStrArr[(*count)++], sizeof(retStrArr[*count]), tmp);

        }
    }
}

int main()
{
    printf("%s", "  start");
    char str[] = "[1,null,2,3,6, 4,5,7,8]";

    printf("\n\n\n%s\n", "start strtok string.");
    int count = 0;
    char retStrArr[100][10] = {0};
    getNum(str, retStrArr, &count);
    for (int i = 0; i < count; ++i) {
        printf("%s\n", retStrArr[i]);
    }

    struct TreeNode *root = malloc(sizeof(struct TreeNode));
    root->val = atoi(retStrArr[0]);
    struct TreeNode *tmp = root;
    root->left = NULL;
    root->right  = NULL;
    struct  TreeNode node[100] = {0};
    node[0] = *root;
    CreatBinaryTree( retStrArr, node, 1, count);
}